//
//  MTInfoVerificationTableView.swift
//  MT
//
//  Created by M on 2019/12/22.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory

@objc
protocol MTInfoVerificationTableViewVerificationTask: NSObjectProtocol {
    @objc optional func infoVerificationTableView(_ tableView: MTInfoVerificationTableView, nickname: String, gender: LocalGenderModel.GenderType, birthday: String, location: String, isAgree: Bool)
    
    @objc optional func infoVerificationTableViewClickRule(selectValue: Int)
}

class MTInfoVerificationTableView: UITableView {
    
    /// 认证代理
    weak var verificationTask: MTInfoVerificationTableViewVerificationTask?
    
    /// 下一步 FooterView
    var footerView: MTInfoVerificationTableFooterView?
    
    /// 列表控制数组
    private var infoTypes: [UserProfileInfos] = [.nickname, .gender, .birthday, .location]
    
    /// 图片 Asset
    var imageAsset: MTAsset? {
        didSet {
            reloadData()
        }
    }
    /// 昵称
    var nickname: String?
    /// 性别
    var gender: LocalGenderModel.GenderType = .unknown
    /// 城市
    var location: String?
    /// 生日
    var birthday: String?

    
    init(frame: CGRect) {
        super.init(frame: frame, style: .grouped)
        setup()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: ------------------ 初始化 ----------------------
extension MTInfoVerificationTableView {
    
    private func setup() {
        backgroundColor = UIColor.theme.background
        delegate = self
        dataSource = self
        separatorStyle = .none
        keyboardDismissMode = .onDrag
        contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        
        for type in infoTypes {
            register(type.cellClass, forCellReuseIdentifier: String(describing: type.cellClass))
        }
    }
    
}

// MARK: ------------------ 其它 ----------------------
private
extension MTInfoVerificationTableView {
    
    /// 本地验证数据
    func locallyVerifyInfos() -> Bool {
//        if imageAsset == nil {
//            AlertManager.presentAlertView(message: "请选择头像")
//            return false
//        }
        if nickname?.count ?? 0 == 0 {
            AlertManager.presentAlertView(message: "请填写昵称")
            return false
        }
        if gender == .unknown {
            AlertManager.presentAlertView(message: "请选择性别")
            return false
        }
        if birthday?.count ?? 0 == 0 {
            AlertManager.presentAlertView(message: "请选择生日")
            return false
        }
        if location?.count ?? 0 == 0 {
            AlertManager.presentAlertView(message: "请选择城市")
            return false
        }
        return true
    }
    
}

// MARK: ------------------ 所有代理 ----------------------
extension MTInfoVerificationTableView: UITableViewDelegate {
    
}

// MARK: ------------------ UI ----------------------
extension MTInfoVerificationTableView: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return infoTypes.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return infoTypes[indexPath.row].cellHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let type = infoTypes[indexPath.row]
        let c = tableView.dequeueReusableCell(withIdentifier: String(describing: type.cellClass), for: indexPath)

        switch type {
        case .portrait:
            guard let cell = c as? MTInfoVerificationPortraitCell else {
                break
            }
            cell.type = type
            cell.asset = imageAsset
            return cell
        
        case .gender:
            guard let cell = c as? MTInfoVerificationGenderCell else {
                break
            }
            cell.delegate = self
            cell.type = type
            cell.selectedType = gender
            return cell
            
        case .nickname:
            guard let cell = c as? MTInfoVerificationInputCell else {
                break
            }
            cell.delegate = self
            cell.type = type
            if      type == .nickname { cell.content = nickname }
            else if type == .birthday { cell.content = birthday }
            else if type == .location { cell.content = location }
            return cell
            
        case .birthday, .location:
            guard let cell = c as? MTInfoVerificationPickerCell else {
                break
            }
            cell.delegate = self
            cell.type = type
            if type == .birthday { cell.content = birthday }
            else if type == .location { cell.content = location }
            return cell
            
        default: break
        }
        
        return c
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return ScreenHeight-NavigationBarHeight-ScreenBottomExtraOffset-StatusBarHeight-250
        }
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0 {
            let v = MTInfoVerificationTableFooterView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight-NavigationBarHeight-ScreenBottomExtraOffset-StatusBarHeight-250))
            v.delegate = self
            v.buttonStr = "下一步"
            v.needShowRule = true
            self.footerView = v
            return v
        }
        return nil
    }
    
}

// MARK: ------------------ 性别回调 ----------------------
extension MTInfoVerificationTableView: MTInfoVerificationGenderCellDelegate {
    
    func genderCell(_ cell: MTInfoVerificationGenderCell, didSelectGender gender: LocalGenderModel.GenderType) {
        self.gender = gender
    }
    
}

// MARK: ------------------ input delegate ----------------------
extension MTInfoVerificationTableView: MTInfoVerificationInputCellDelegate {
    
    func inputCell(_ cell: BaseMTInfoVerificationCell, infoType: UserProfileInfos, didInputText text: String?) {
        switch infoType {
        case .nickname:
            self.nickname = text
            break
        case .birthday:
            self.birthday = text
            break
        case .location:
            self.location = text
            break
        default:
            break
        }
    }
    
}

// MARK: ------------------ FooterView 代理回调 ----------------------
extension MTInfoVerificationTableView: MTInfoVerificationTableFooterViewDelegate {
    
    func tableFooterViewDidClickButton(_ footerView: MTInfoVerificationTableFooterView) {
        if !locallyVerifyInfos() { return }
//        guard let asset = imageAsset else { return }
        if nickname?.utf8.count ?? 0 > UserProfileInfos.nickname.maximumTextCount ?? 0 {
            AlertManager.presentAlertView(message: "昵称超出字数", duration: 1)
            return
        }
        if let verificationTask = verificationTask, let nickname = nickname, let birthday = birthday, let location = location, gender != .unknown {
            verificationTask.infoVerificationTableView?(self,nickname: nickname, gender: self.gender, birthday: birthday, location: location,isAgree: (self.footerView?.agreeButton.isSelected)!)
        }
//        if let verificationTask = verificationTask, let nickname = nickname, let birthday = birthday, let location = location, gender != .unknown {
//            MTAssetLibrary.default.requestImage(withAsset: asset.asset, photoWidth: ScreenWidth, progressHandler: nil, errorHandler: nil) { [weak self] (image, info, isDegraded) in
//                guard let weakSelf = self, let image = image, let isDegraded = isDegraded else { return }
//                if !isDegraded {
//                    weakSelf.endEditing(true)
//                    verificationTask.infoVerificationTableView?(weakSelf, willSubmitInfosWithPortrait: image, nickname: nickname, gender: weakSelf.gender, birthday: birthday, location: location)
//                }
//            }
//        }
    }
    
    func userAgreement() {
        if let verificationTask = verificationTask {
            verificationTask.infoVerificationTableViewClickRule?(selectValue: 0)
        }
    }
    
    func privacy() {
        if let verificationTask = verificationTask {
            verificationTask.infoVerificationTableViewClickRule?(selectValue: 1)
        }
    }
    
}

